package horncomb.bpm.process.instance;

import java.util.UUID;

import horncomb.bpm.process.core.ProcessDefinition;
import horncomb.bpm.process.core.ProcessInstance;
import horncomb.bpm.process.core.ProcessInstanceCreator;
import horncomb.bpm.process.core.Token;
import horncomb.bpm.process.core.entity.ProcessInstanceEntity;
import horncomb.bpm.process.entity.DefaultProcessInstanceEntity;
import horncomb.bpm.process.support.BizEntityRefer;

/**
 * 简单流程实例创建器
 * @author Daniel
 */
public class DefaultProcessInstanceCreator implements ProcessInstanceCreator {

	/**
	 * {@inheritDoc}
	 */
	public ProcessInstance create(Token parent,
			ProcessDefinition processDefinition, Object contextModel) {
		DefaultProcessInstance processInst = null;
		ProcessInstanceEntity entity = null;
		if (contextModel instanceof ProcessInstanceEntity) {
			entity = (ProcessInstanceEntity) contextModel;
		} else {
			entity = new DefaultProcessInstanceEntity();
			entity.setId(processDefinition.getId() + ":" + UUID.randomUUID());
		}
		if (contextModel instanceof BizEntityRefer) {
			entity.setBizDefinitionId(((BizEntityRefer) contextModel)
					.getBizDefinitionId());
			entity.setBizEntityId(((BizEntityRefer) contextModel)
					.getBizEntityId());
		}
		if (parent == null) {
			processInst = new DefaultProcessInstance(processDefinition.getId(),
					entity);
		} else {
			processInst = new DefaultProcessInstance(processDefinition.getId(),
					entity, parent.getId());
		}
		processInst.setName(processDefinition.getName());
		return processInst;
	}
}
